import { useInfinite } from './infinite'
import { useSortGridData } from './sort-grid-data'

export function useInfiniteWithSorting({ request, params, limit = 12 }) {
  const {
    dataList: _dataList,
    dataExtra,
    loading,
    noMore,
    errorMsg,
    init: _init,
    refresh: _refresh,
    nextPage: _nextPage,
    destroy: _destroy,
  } = useInfinite({ request, params, limit })

  const { dataList, colsList, input, reset: sortingDataReset } = useSortGridData()

  function init(onData) {
    _init(onDataHnadler(onData))
  }

  function refresh({ newRequest = request, newParams = params, newLimit = limit } = {}, onData) {
    sortingDataReset()
    _refresh({ newRequest, newParams, newLimit }, onDataHnadler(onData))
  }

  function nextPage(onData) {
    _nextPage(onDataHnadler(onData))
  }

  function onDataHnadler(onData) {
    return (...args) => {
      const newLen = _dataList.value.length
      const oldLen = dataList.value.length
      if (newLen > oldLen) {
        input(_dataList.value.slice(oldLen))
      }

      onData?.apply(this, args)
    }
  }

  function destroy() {
    _destroy()
  }

  return {
    dataList,
    colsList,
    dataExtra,
    loading,
    noMore,
    errorMsg,
    init,
    refresh,
    nextPage,
    destroy,
  }
}
